import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

//编写代码, 实现线程池案例
class MyThreadPool1{
    private BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1000);
    private int max = 0;//记录最大值
    private List<Thread> list = new ArrayList<>();

    public MyThreadPool1(int c,int max){
        //c 是核心线程数,max是最大线程数
        for (int i = 0; i <c ; i++) {
            Thread t = new Thread(()->{
                try {
                    while (true){
                        //让同一线程将所有任务都执行一遍
                        Runnable runnable = blockingQueue.take();
                        runnable.run();
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            });
            t.start();
            list.add(t);//将线程放入表中,防止超过最大线程数
        }
    }

    public void submit(Runnable runnable) throws InterruptedException {
        //用来提交任务和创建非核心线程
        blockingQueue.put(runnable);
        if(blockingQueue.size()>=500&&list.size()<=max){
            //证明放任务的阻塞队列已经到达峰值,且线程数没有到最大线程数,此时可以进行新线程创建,然后执行任务
            Thread t = new Thread(()->{
                try {
                    while (true){
                        //让同一线程将所有任务都执行一遍
                        Runnable task = blockingQueue.take();
                        task.run();
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
}
public class Homework1 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool1 myThreadPool1 = new MyThreadPool1(10,20);
        for (int i = 0; i <500 ; i++) {
            int id = i;
            myThreadPool1.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("count: "+id);
                }
            });
        }
    }
}
